package com.bml.architect.transaction;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

/**
 * 事务的监听器
 *  * 当rocketmq向broker发送half消息的时候，half消息返回过后，可执行本地事务的方法，就是executeLocalTransaction
 *      * 在这个方法里面就可以执行自己的事务逻辑，最后返回一个事务状态
 *      * COMMIT_MESSAGE：向broker中的主题发送一个mq消息，下游服务可见
 *      * ROLLBACK_MESSAGE：向broker发送的一个回滚的指令，消息被丢弃
 *      * UNKNOW：broker会存储起来，过一段时间过来回查，调用了checkLocalTransaction回查本地事务的状态，然后
 *      * 最终也会返回一个事务的状态，根据状态来判断是提交、回滚还是进行回查
 */
public class TransactionListenerImpl implements TransactionListener {

    @Override
    public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        String tag = msg.getTags();
        LocalTransactionState state = LocalTransactionState.UNKNOW;
        if (tag.equals("TagA")) {
            state= LocalTransactionState.COMMIT_MESSAGE;
        }
        if (tag.equals("TagB")) {
            state= LocalTransactionState.ROLLBACK_MESSAGE;
        }
        System.out.println(state);
        return  state;
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt msg) {
        String tags = msg.getTags();
        if (StringUtils.contains(tags, "TagC")) {
            return LocalTransactionState.COMMIT_MESSAGE;
        } else if (StringUtils.contains(tags, "TagD")) {
            return LocalTransactionState.ROLLBACK_MESSAGE;
        } else {
            return LocalTransactionState.UNKNOW;
        }
    }
}
